from django.db import models
from django.urls import reverse
import uuid
from django.conf import settings

class Category(models.Model):
    title = models.CharField('分类名称', max_length=200)
    parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, verbose_name='父级分类',
                               related_name='children')
    is_active = models.BooleanField('是否启用', default=True)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)

    class Meta:
        verbose_name = '商品分类'
        verbose_name_plural = '商品分类'

    def __str__(self):
        return self.title


class Product(models.Model):
    name = models.CharField('商品名称', max_length=200)
    sku = models.CharField('商品编码', max_length=50, unique=True, default=uuid.uuid4)
    img = models.ImageField('主图', upload_to='products/')
    category = models.ForeignKey(Category, on_delete=models.PROTECT, verbose_name='分类', related_name='products')
    price = models.DecimalField('售价', max_digits=10, decimal_places=2)
    cost_price = models.DecimalField('成本价', max_digits=10, decimal_places=2)
    stock = models.IntegerField('库存数量', default=0)
    description = models.TextField('商品描述',null=True, blank=True)
    is_active = models.BooleanField('是否上架', default=True)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        verbose_name = '商品'
        verbose_name_plural = '商品'

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('product_detail', kwargs={'pk': self.pk})

    @property
    def profit(self):
        """计算利润"""
        return self.price - self.cost_price

    @property
    def is_in_stock(self):
        """是否有库存"""
        return self.stock > 0


class ProductImage(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name='商品', related_name='images')
    image = models.ImageField('图片', upload_to='product_images/')
    alt_text = models.CharField('图片描述', max_length=200, blank=True)
    is_main = models.BooleanField('是否主图', default=False)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)

    class Meta:
        verbose_name = '商品图片'
        verbose_name_plural = '商品图片'

    def __str__(self):
        return f"{self.product.name} - {self.alt_text or '图片'}"


class Order(models.Model):
    ORDER_STATUS = (
        ('pending', '待付款'),
        ('paid', '已付款'),
        ('shipped', '已发货'),
        ('delivered', '已收货'),
        ('cancelled', '已取消'),
        ('refunded', '已退款'),
    )

    order_number = models.CharField('订单号', max_length=50, unique=True, default=uuid.uuid4)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='用户', related_name='orders')
    product = models.ForeignKey(Product, on_delete=models.PROTECT, verbose_name='商品', related_name='orders')
    price = models.DecimalField('单价', max_digits=10, decimal_places=2)
    quantity = models.PositiveIntegerField('数量', default=1)
    status = models.CharField('订单状态', max_length=20, choices=ORDER_STATUS, default='pending')
    shipping_address = models.ForeignKey('Address', on_delete=models.PROTECT, verbose_name='收货地址',
                                         related_name='orders')
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        verbose_name = '订单'
        verbose_name_plural = '订单'

    def __str__(self):
        return f"订单 {self.order_number}"

    def save(self, *args, **kwargs):
        if not self.order_number:
            self.order_number = str(uuid.uuid4())[:50]
        # 自动设置订单单价为商品当前价格
        if not self.price and self.product:
            self.price = self.product.price
        super().save(*args, **kwargs)

    @property
    def total_amount(self):
        """计算订单总金额"""
        return self.price * self.quantity


class OrderItem(models.Model):
    """订单项模型 - 连接订单和商品"""
    order = models.ForeignKey(Order, on_delete=models.CASCADE, verbose_name='订单', related_name='items')
    product = models.ForeignKey(Product, on_delete=models.PROTECT, verbose_name='商品', related_name='order_items')
    quantity = models.PositiveIntegerField('数量', default=1)
    price = models.DecimalField('单价', max_digits=10, decimal_places=2)

    class Meta:
        verbose_name = '订单项'
        verbose_name_plural = '订单项'


    def __str__(self):
        return f"{self.product.name} x {self.quantity}"

    def save(self, *args, **kwargs):
        # 自动设置订单项单价为商品当前价格
        if not self.price and self.product:
            self.price = self.product.price
        super().save(*args, **kwargs)

    @property
    def subtotal(self):
        """小计金额"""
        return self.quantity * self.price


class Address(models.Model):
    """收货地址模型"""
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='用户', related_name='addresses')
    recipient_name = models.CharField('收货人', max_length=100)
    phone = models.CharField('联系电话', max_length=20)
    province = models.CharField('省份', max_length=50)
    city = models.CharField('城市', max_length=50)
    district = models.CharField('区县', max_length=50)
    street = models.CharField('详细地址', max_length=200)
    is_default = models.BooleanField('默认地址', default=False)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)

    class Meta:
        verbose_name = '收货地址'
        verbose_name_plural = '收货地址'

    def __str__(self):
        return f"{self.recipient_name} - {self.province}{self.city}{self.district}{self.street}"

    def get_full_address(self):
        """获取完整地址"""
        return f"{self.province}{self.city}{self.district}{self.street}"


class UserProfile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='用户', related_name='profile')
    phone = models.CharField('手机号', max_length=20, blank=True)
    avatar = models.ImageField('头像', upload_to='head/', blank=True)
    birth_date = models.DateField('生日', null=True, blank=True)


    class Meta:
        verbose_name = '用户资料'
        verbose_name_plural = '用户资料'

    def __str__(self):
        return f"{self.user.username} 的资料"

    @property
    def default_address(self):
        """获取默认收货地址"""
        return self.user.addresses.filter(is_default=True).first()

    def get_order_count(self):
        """获取用户订单数量"""
        return self.user.orders.count()